<template>
  <basic-dialog
    title="自签证书"
    :visible="visible"
    :loading="loading"
    :width="448"
    has-footer
    @closed="handleClose"
    @submit="handleSubmit"
  >
    <el-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      require-asterisk-position="right"
      label-width="100px"
      label-position="top"
      @submit.prevent
    >
      <el-form-item label="域名" prop="domain">
        <el-input
          v-model="formState.domain"
          :rows="5"
          type="textarea"
          placeholder="请输入域名，一行一个，支持*和IP地址"
        />
      </el-form-item>

      <el-form-item label="备注" class="hide-star" prop="description">
        <el-input
          v-model.trim="formState.description"
          maxlength="20"
          placeholder="请输入备注"
        />
      </el-form-item>

      <el-form-item prop="key_type" label="密钥算法">
        <el-select v-model="formState.key_type" class="w-full">
          <el-option
            v-for="item in ALGORITHM_OPTS"
            :key="item.label"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="有效期" prop="time">
        <section class="input_with_select">
          <el-input-number
            v-model.number="formState.time"
            :controls="false"
            :max="formState.unit === 'year' ? 100 : 365"
            :min="1"
            placeholder="请输入"
            class="flex-1"
          >
          </el-input-number>
          <el-select v-model="formState.unit" style="width: 60px">
            <el-option label="年" value="year" />
            <el-option label="天" value="day" />
          </el-select>
        </section>
      </el-form-item>

      <el-form-item prop="auto_renew" label="">
        <el-checkbox v-model="formState.auto_renew">自动续签</el-checkbox>
      </el-form-item>
    </el-form>
  </basic-dialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormItemRule } from 'element-plus'

import type { ApplySelfCertParams, SelfCertModel } from '@/apis/model/selfCert'
import { ALGORITHM_OPTS } from '@/config/constant/cert'
interface IProps {
  visible: boolean
  record: SelfCertModel
  loading: boolean
}
interface IEmits {
  (event: 'update:visible', value: boolean): void
  (event: 'update:loading', value: boolean): void
}

const props = defineProps<IProps>()
const emit = defineEmits<IEmits>()
const formRef = ref<FormInstance>()
interface IFormState extends ApplySelfCertParams {
  domain: string
  key_type: any
  time: any
}
const formState = reactive<IFormState>({
  auto_renew: false,
  description: '',
  domain: '',
  domain_list: [],
  key_type: ALGORITHM_OPTS[0].value,
  self_ca_id: '',
  time: undefined,
  unit: 'year'
})
const validateDomain = (_rule: any, value: any, callback: any) => {
  if (!value) return callback()
  const valueList = value.split('\n').filter(Boolean)
  const num = valueList.length
  let isOut
  valueList.map((item: string) => {
    item = item.trim()
    if (item.length > 100) {
      return new Error('域名总长度不能超过100个字符')
    }
    if (item.startsWith('*.')) {
      item = item.substring(2, item.length - 1)
    }
    if (domainReg.test(item) || ipv4Reg.test(item)) {
      isOut = false
    } else {
      isOut = true
    }
  })
  if (isOut) {
    callback(new Error('域名格式不正确'))
  } else if (num > 10) {
    callback(new Error('已超过配置上限，请核对'))
  } else {
    callback()
  }
}
const rules: Record<string, FormItemRule[]> = {
  domain: [
    { required: true, message: '请输入域名', trigger: 'blur' },
    {
      validator: validateDomain
    }
  ],
  key_type: [{ required: true, message: '请选择', trigger: 'change' }],
  time: [{ required: true, message: '请输入有效期', trigger: 'blur' }]
}
const handleClose = () => {
  emit('update:visible', false)
  formRef.value?.resetFields()
}
async function handleSubmit() {
  await formRef.value?.validate()
  const params = {
    ...omitReactive(formState, ['domain']).value,
    domain_list: formState.domain.split('\n').filter(Boolean),
    self_ca_id: props.record?.id!,
    time: +formState.time
  }
  emit('update:loading', true)
  await applySelfCertApi(params)
    .then(() => {
      handleClose()
      ToastUtils.success('操作成功')
    })
    .finally(() => emit('update:loading', false))
}
</script>

<style lang="scss" scoped></style>
